package com.zhiqianbao.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import com.zhiqianbao.R;
import com.zhiqianbao.adapter.BankListAdapter;
import com.zhiqianbao.entity.Area;
import com.zhiqianbao.entity.Bank;
import com.zhiqianbao.entity.Code;
import com.zhiqianbao.entity.Result;
import com.zhiqianbao.shared.SharedPreferanceUtils;
import com.zhiqianbao.utils.ClickControlUtils;
import com.zhiqianbao.utils.Constants;
import com.zhiqianbao.utils.DialogTypeUtils;
import com.zhiqianbao.utils.HttpUtils;
import com.zhiqianbao.utils.MyAlertDialog;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.trinea.android.common.util.StringUtils;

/**
 * Created by Liang on 2015/12/16.
 */
public class BaseActivity extends AppCompatActivity {
    private Button returnButton;
    private EditText bankEdit;
    private EditText proviceEdit;
    private EditText cityEdit;
    private EditText areaEdit;
    private String pText;
    private String cText;
    private String aText;
    private AlertDialog oneDialog;
    private AlertDialog twoDialog;
    private AlertDialog threeDialog;
    private AlertDialog dialog;
    private Bank bank;
    private List<Bank> banks;
    private EditText bankId;
    private Dialog waitDialog;
    private EditText bankName;
    private AlertDialog.Builder Alertbuilder;
    private final String mPackageNameUmeng = this.getClass().getName();

    protected void init() {
        try{
            //ScreenManager.getScreenManager().pushActivity(this);
            returnButton = (Button) findViewById(R.id.button_ruturn);
            if (null != returnButton) {
                returnButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });
            }
        }catch (Exception e){

        }

    }

    protected void showWaitDialog() {
        if(!isFinishing()) {
            waitDialog = new Dialog(this, R.style.DialogStyle);
            LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            View waitView = layoutInflater.inflate(R.layout.loading_dialog, null);
            WindowManager.LayoutParams params = new WindowManager.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
            params.alpha = 0.0F;
            waitDialog.addContentView(waitView, params);

//        waitDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
//            @Override
//            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
//
//                switch(keyCode){
//                    case KeyEvent.KEYCODE_HOME:return true;
//                    case KeyEvent.KEYCODE_BACK:return true;
//                    case KeyEvent.KEYCODE_CALL:return true;
//                    case KeyEvent.KEYCODE_SYM: return true;
//                    case KeyEvent.KEYCODE_VOLUME_DOWN: return true;
//                    case KeyEvent.KEYCODE_VOLUME_UP: return true;
//                    case KeyEvent.KEYCODE_STAR: return true;
//                }
//
//                return false; //默认返回 false
//            }
//        });

            waitDialog.show();
        }
    }

    protected void closeWaitDialog() {
        if (null != waitDialog) {
            waitDialog.cancel();
            waitDialog = null;
        }
    }


    /**
     * 短时间吐司
     */
    static Toast toastShort;

    public Toast showShortToast1(final String message) {
        if (toastShort == null) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    toastShort = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT);
                }
            });
        } else {
            toastShort.setText(message);
            toastShort.setDuration(Toast.LENGTH_SHORT);
        }
        toastShort.setGravity(Gravity.CENTER, 0, 0);
        toastShort.show();
        return toastShort;
    }
    public Toast showShortToast2(String message) {
        if (toastShort == null) {
            toastShort = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG);
        } else {
            toastShort.setText(message);
            toastShort.setDuration(Toast.LENGTH_SHORT);
        }
        toastShort.setGravity(Gravity.CENTER, 0, 0);
        toastShort.show();
        return toastShort;
    }


    private ClickControlUtils clickUtil = new ClickControlUtils();

    /**
     * 检查是否双击过快
     *
     * @return
     * @author Wall
     */
    public boolean fasterClickCheck() {
        if (clickUtil != null) {
            return clickUtil.isEvenFastCheck(Constants.DOUBLE_CLICKED_MAXTIME);
        }
        return false;
    }

    /**
     * 弹出选择地区框
     *
     * @param bankEdit
     * @param proviceEdit
     * @param cityEdit
     * @param areaEdit
     */
    protected void showAreaDialog(EditText bankEdit, EditText proviceEdit, EditText cityEdit, EditText areaEdit) {
        this.bankEdit = bankEdit;
        this.proviceEdit = proviceEdit;
        this.cityEdit = cityEdit;
        this.areaEdit = areaEdit;
        new ProviceAsyncTask().execute();
    }

    private class ProviceAsyncTask extends AsyncTask<Void, Void, Result<List<Area>>> {

        protected void onPreExecute() {
            showWaitDialog();
        }

        @Override
        protected Result<List<Area>> doInBackground(Void... params) {
            String result = HttpUtils.httpPostString(Constants.API_ROOT + "/basic/areas");
            if (StringUtils.isBlank(result)) {
                return null;
            }
            Result<List<Area>> resultObject = Result.fromJson(result, List.class);
            return resultObject;
        }

        @Override
        protected void onPostExecute(final Result<List<Area>> result) {
            if (result == null) {
                showShortToast1("连接超时！");
            } else {
                //请求成功
                if (Constants.DEFAULT_SUCCESS_CODE.equals(result.getCode())) {
                    AlertDialog.Builder oneBuilder = new AlertDialog.Builder(BaseActivity.this);
                    LayoutInflater oneInflater = getLayoutInflater();
                    View oneView = oneInflater.inflate(R.layout.activity_city_one, null);
                    //省份的ListView加载数据
                    ListView oneListView = (ListView) oneView.findViewById(R.id.listView_cityOne);
                    final List<String> provices = new ArrayList<>();
                    for (Object area : result.getData()) {
                        LinkedTreeMap map = (LinkedTreeMap) area;
                        provices.add((String) map.get("name"));
                    }
                    oneListView.setAdapter(new ArrayAdapter<String>(BaseActivity.this, android.R.layout.simple_list_item_1, provices));
                    oneBuilder.setView(oneView);
                    oneDialog = oneBuilder.create();
                    //绑定点击事件
                    oneListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            Object provice = result.getData().get(position);
                            LinkedTreeMap proviceMap = (LinkedTreeMap) provice;
                            String pname = (String) proviceMap.get("name");

                            pText = pname;
                            HashMap<String, String> param = new HashMap<>();
                            Double proviceId = (Double) proviceMap.get("id");
                            param.put("id", proviceId.intValue() + "");
                            new CityAsyncTask().execute(param);
                        }
                    });
                    oneDialog.show();
                } else {
                    showShortToast1(result.getMsg());
                }
            }
            closeWaitDialog();
        }
    }

    private class CityAsyncTask extends AsyncTask<Map, Void, Result<List<Area>>> {
        protected void onPreExecute() {
            showWaitDialog();
        }

        @Override
        protected Result<List<Area>> doInBackground(Map... params) {
            String result = HttpUtils.httpPostString(Constants.API_ROOT + "/basic/areas", params[0]);
            if (StringUtils.isBlank(result)) {
                return null;
            }
            Result<List<Area>> resultObject = Result.fromJson(result, List.class);
            return resultObject;
        }

        @Override
        protected void onPostExecute(final Result<List<Area>> result) {
            if (result == null) {
                showShortToast1("连接超时！");
            } else {
                //请求成功
                if (Constants.DEFAULT_SUCCESS_CODE.equals(result.getCode())) {
                    AlertDialog.Builder twoBuilder = new AlertDialog.Builder(BaseActivity.this);
                    LayoutInflater twoInflater = getLayoutInflater();
                    View twoView = twoInflater.inflate(R.layout.activity_city_two, null);
                    //市的ListView加载数据
                    ListView twoListView = (ListView) twoView.findViewById(R.id.listView_citytwo);
                    final List<String> cities = new ArrayList<>();
                    for (Object area : result.getData()) {
                        LinkedTreeMap map = (LinkedTreeMap) area;
                        cities.add((String) map.get("name"));
                    }
                    twoListView.setAdapter(new ArrayAdapter<String>(BaseActivity.this, android.R.layout.simple_list_item_1, cities));
                    twoBuilder.setView(twoView);
                    twoDialog = twoBuilder.create();
                    //绑定点击事件
                    twoListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            Object city = result.getData().get(position);
                            LinkedTreeMap cityMap = (LinkedTreeMap) city;
                            String cname = (String) cityMap.get("name");

                            cText = cname;
                            HashMap<String, String> param = new HashMap<>();
                            Double cityId = (Double) cityMap.get("id");
                            Log.i(this.getClass().toString(), cityId.intValue() + "");
                            param.put("id", cityId.intValue() + "");
                            new AreaAsyncTask().execute(param);
                        }
                    });
                    twoDialog.show();
                } else {
                    showShortToast1(result.getMsg());
                }
            }
            closeWaitDialog();
        }
    }

    private class AreaAsyncTask extends AsyncTask<Map, Void, Result<List<Area>>> {
        protected void onPreExecute() {
            showWaitDialog();
        }

        @Override
        protected Result<List<Area>> doInBackground(Map... params) {
            String result = HttpUtils.httpPostString(Constants.API_ROOT + "/basic/areas", params[0]);
            if (StringUtils.isBlank(result)) {
                return null;
            }
            Result<List<Area>> resultObject = Result.fromJson(result, List.class);
            return resultObject;
        }

        @Override
        protected void onPostExecute(final Result<List<Area>> result) {
            if (result == null) {
                showShortToast1("连接超时！");
            } else {
                //请求成功
                if (Constants.DEFAULT_SUCCESS_CODE.equals(result.getCode())) {
                    AlertDialog.Builder threeBuilder = new AlertDialog.Builder(BaseActivity.this);
                    LayoutInflater threeInflater = getLayoutInflater();
                    View threeView = threeInflater.inflate(R.layout.activity_city_three, null);
                    //区的ListView加载数据
                    ListView threeListView = (ListView) threeView.findViewById(R.id.listView_cityThree);
                    final List<String> areas = new ArrayList<>();
                    for (Object area : result.getData()) {
                        LinkedTreeMap map = (LinkedTreeMap) area;
                        areas.add((String) map.get("name"));
                    }
                    threeListView.setAdapter(new ArrayAdapter<String>(BaseActivity.this, android.R.layout.simple_list_item_1, areas));
                    threeBuilder.setView(threeView);
                    threeDialog = threeBuilder.create();
                    //绑定点击事件
                    threeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            Object aa = result.getData().get(position);
                            LinkedTreeMap areaMap = (LinkedTreeMap) aa;
                            String aname = (String) areaMap.get("name");
                            if (null != proviceEdit) {
                                proviceEdit.setText(pText);
                            }
                            if (null != cityEdit) {
                                cityEdit.setText(cText);
                            }
                            if (null != areaEdit) {
                                areaEdit.setText(aname);
                            }
                            aText = aname;

                            String bankAddress = "";
                            if (pText.equals(cText)) {
                                bankAddress = cText + aText;
                            } else {
                                bankAddress = pText + cText + aText;
                            }
                            bankEdit.setText(bankAddress);
                            threeDialog.cancel();
                            twoDialog.cancel();
                            oneDialog.cancel();
                        }
                    });
                    threeDialog.show();
                } else {
                    showShortToast1(result.getMsg());
                }
            }
            closeWaitDialog();
        }
    }


    protected void showSelectDialog(final List<String> list, final EditText editText, String title) {
        AlertDialog.Builder builder = new AlertDialog.Builder(BaseActivity.this);

        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(R.layout.activity_bank_one, null);
        TextView marryTitle = (TextView) view.findViewById(R.id.textview_bank_title);
        marryTitle.setText(title);
        //选择列表
        ListView listView = (ListView) view.findViewById(R.id.listView_bank);
        listView.setAdapter(new ArrayAdapter<String>(BaseActivity.this, android.R.layout.simple_list_item_1, list));
        Alertbuilder.setView(view);
        final AlertDialog dialog = Alertbuilder.create();
        dialog.show();
        //列表绑定选择事件
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String text = list.get(position);
                editText.setText(text);
                dialog.cancel();
            }
        });
        //取消按钮
        TextView bankDialogButton = (TextView) view.findViewById(R.id.bank_dialog_button);
        bankDialogButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.cancel();
            }
        });
    }


    protected void showSelectDialogFromCode(final List<Code> list, final EditText editText, final EditText keyText, String title) {
         AlertDialog.Builder builder = new AlertDialog.Builder(BaseActivity.this);
        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(R.layout.activity_bank_one, null);
        TextView marryTitle = (TextView) view.findViewById(R.id.textview_bank_title);
        marryTitle.setText(title);
        //选择列表
        ListView listView = (ListView) view.findViewById(R.id.listView_bank);
        List<String> nameList = new ArrayList<>();
        for (Code code : list) {
            nameList.add(code.getValue());
        }
        listView.setAdapter(new ArrayAdapter<String>(BaseActivity.this, android.R.layout.simple_list_item_1, nameList));
        builder.setView(view);
        dialog = builder.create();
        dialog.show();
        //列表绑定选择事件
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Code code = list.get(position);
                if (code!=null){
                    editText.setText(code.getValue());
                    keyText.setText(code.getKey());
                }

                dialog.cancel();
            }
        });
        //取消按钮
        TextView bankDialogButton = (TextView) view.findViewById(R.id.bank_dialog_button);
        bankDialogButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.cancel();
            }
        });
    }

    public Bitmap stringtoBitmap(String string) {
        //将字符串转换成Bitmap类型
        Bitmap bitmap = null;
        try {
            byte[] bitmapArray;
            bitmapArray = Base64.decode(string, Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return bitmap;
    }

    protected void recycleBitmap(Bitmap bitmap) {
        if (bitmap != null) {
            bitmap.recycle();
            bitmap = null;
        }
    }


    EditText currentValue;
    EditText currentKey;
    String currentTitle;
    Gson gson = new Gson();

    /**
     * @param title
     * @param positive
     * @param negative
     */
    public void showAlertMsgDialog1(String title, String positive, String negative) {
        MyAlertDialog alertDialog = new MyAlertDialog(this).builder().setTitle(title).setPositiveButton(positive, new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                startActivity(new Intent(getApplicationContext(), ProcessActivity.class));
            }
        }).setNegativeButton(negative, new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

            }
        });
        alertDialog.show();
    }

    /**
     * @param title
     * @param positive
     * @param negative
     */
    public void showAlertMsgDialog(String title, String positive, String negative) {
        MyAlertDialog alertDialog = new MyAlertDialog(this).builder().setTitle(title).setPositiveButton(positive, new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated methoub
                String emergency = SharedPreferanceUtils.getEmergency();
                Log.i("保存的..", emergency);
                if (!TextUtils.isEmpty(SharedPreferanceUtils.getEmergency())) {
                    if (SharedPreferanceUtils.getEmergency().equals("1") || SharedPreferanceUtils.getEmergency().equals("2")) {
                        Intent intent = new Intent(getApplicationContext(), ProcessActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                        finish();
                    } else {
                        startActivity(new Intent(getApplicationContext(), ThirdActivity.class));
                        finish();
                    }
                } else {
                    startActivity(new Intent(getApplicationContext(), ThirdActivity.class));
                    finish();
                }


            }
        }).setNegativeButton(negative, new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

            }
        });
        alertDialog.show();
    }

    /**
     * 保存二维码图片
     *
     * @param bmp
     */
    public void saveCroppedImage(Bitmap bmp) {
        File file = new File("/sdcard/myFolder");
        if (!file.exists())
            file.mkdir();

        file = new File("/sdcard/temp.jpg".trim());
        String fileName = file.getName();
        String mName = fileName.substring(0, fileName.lastIndexOf("."));
        String sName = fileName.substring(fileName.lastIndexOf("."));

        // /sdcard/myFolder/temp_cropped.jpg
        String newFilePath = "/sdcard/myFolder" + "/" + mName + "_cropped" + sName;
        file = new File(newFilePath);
        try {
            file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 50, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    /**
     * 远程获取数据 弹出选择框
     *
     * @param category 类型
     * @param title    选择框标题
     * @param value    显示选择的值
     * @param key      记住选择的key
     */
    protected void alertSelectDialog(final String category, final String title, final EditText value, final EditText key) {
        currentValue = value;
        currentKey = key;
        currentTitle = title;
        List<Code> codes = new ArrayList<>();
        if(category.equals(Constants.CODE_CHILDREN)){
            codes=DialogTypeUtils.getCodes(getResources(),R.array.child_type,
                    R.array.child_type_code);
        }
        else if(category.equals(Constants.CODE_WORKJOB)){
            codes=DialogTypeUtils.getCodes(getResources(),R.array.job_type,
                    R.array.job_type_code);
        }
        //弹出选择框
        showSelectDialogFromCode(codes, currentValue, currentKey, currentTitle);
    }


    protected void alertBankSelectDialog(final EditText bankName, final EditText bankId) {
        banks= DialogTypeUtils.getBanks(getResources());
        final AlertDialog.Builder bankBuilder = new AlertDialog.Builder(BaseActivity.this);
        LayoutInflater bankInflater = getLayoutInflater();
        View bankView = bankInflater.inflate(R.layout.activity_bank_one, null);
        ListView bankListView = (ListView) bankView.findViewById(R.id.listView_bank);
        TextView bankCancelButton = (TextView) bankView.findViewById(R.id.bank_dialog_button);
        bankListView.setAdapter(new BankListAdapter(BaseActivity.this, banks));
        bankBuilder.setView(bankView);
        final AlertDialog bankDialog = bankBuilder.create();
        bankDialog.show();
        //绑定关闭银行选择框事件
        bankCancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bankDialog.cancel();
            }
        });

        bankListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Bank bank = banks.get(position);
                bankName.setText(bank.getName());
                bankId.setText(bank.getId() + "");
                bankDialog.cancel();
            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(mPackageNameUmeng);
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(mPackageNameUmeng);
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dialog != null && dialog.isShowing()) {
            dialog.cancel();
            dialog.dismiss();
            dialog = null;
        }
        if (waitDialog != null && waitDialog.isShowing()) {
            waitDialog.cancel();
            waitDialog.dismiss();
            waitDialog = null;
        }
    }
}


